package com.resys.server.controller.admin;

import com.resys.annotation.GlobalInterceptor;
import com.resys.entity.dto.MeetingRoomDto;
import com.resys.entity.dto.TokenCustomerDto;
import com.resys.entity.dto.TokenUserInfoDto;
import com.resys.entity.enums.DateTimePatternEnum;
import com.resys.entity.po.Device;
import com.resys.entity.po.Meetingroom;
import com.resys.entity.po.Roomdevice;
import com.resys.entity.query.DeviceQuery;
import com.resys.entity.query.MeetingroomQuery;
import com.resys.entity.query.ReservationorderQuery;
import com.resys.entity.query.RoomdeviceQuery;
import com.resys.entity.vo.ResponseVO;
import com.resys.entity.vo.StatusVo;
import com.resys.exception.BusinessException;
import com.resys.mappers.ReservationorderMapper;
import com.resys.server.controller.ABaseController;
import com.resys.service.CommentService;
import com.resys.service.MeetingroomService;
import com.resys.service.RoomdeviceService;
import com.resys.service.RoomshowService;
import com.resys.service.impl.DeviceServiceImpl;
import com.resys.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Stream;

@Transactional
@RestController("MeetingRoomController")
@Slf4j
@Api(tags = "管理员模块-会议室管理接口")
@RequestMapping("/admin/meetingRoom")
public class MeetingRoomController extends ABaseController {
    @Resource
    private MeetingroomService meetingroomService;
    @Resource
    private RoomdeviceService roomdeviceService;
    @Autowired
    private DeviceServiceImpl deviceService;
    @Resource
    private RoomshowService roomshowService;
    @Resource
    private CommentService commentService;
    private final String UPLOAD_PATH = System.getProperty("user.dir") + "/static/meetingroom/";
    @ApiOperation("获取会议室列表")
    @GetMapping
    public ResponseVO list(){
        MeetingroomQuery query  = new MeetingroomQuery();
       List<Meetingroom> list = meetingroomService.findListByParam(query);
       return getSuccessResponseVO(list);
    }
    @ApiOperation("删除该会议室")
    @PutMapping
    public ResponseVO delete(Integer roomId){
        meetingroomService.deleteMeetingroomByRoomId(roomId);
        return getSuccessResponseVO("删除成功");
    }
    @ApiOperation("新增会议室")
    @PostMapping("/add")
    public ResponseVO add(@RequestBody MeetingRoomDto meetingRoomDto){
        Meetingroom meetingroom = new Meetingroom();
        Meetingroom testRoom= meetingroomService.getMeetingroomByName(meetingRoomDto.getName());
        if(testRoom!=null){
            return getServerErrorResponseVO("该会议室名字已存在");
        }
        BeanUtils.copyProperties(meetingRoomDto,meetingroom);
        meetingroomService.add(meetingroom);
        return getSuccessResponseVO("新增成功");
    }
    @ApiOperation("修改会议室信息")
    @PostMapping("/update")
    public ResponseVO update(@RequestBody Meetingroom meetingroom){
        Meetingroom testRoom= meetingroomService.getMeetingroomByName(meetingroom.getName());
        Meetingroom room = meetingroomService.getMeetingroomByRoomId(meetingroom.getRoomId());
        if(testRoom!=null&&!room.getName().equals(testRoom.getName())){
            return getServerErrorResponseVO("该会议室名字已存在");
        }
        meetingroomService.updateMeetingroomByRoomId(meetingroom, meetingroom.getRoomId());
        return getSuccessResponseVO("修改成功");
    }
    @ApiOperation("模糊搜索会议室")
    @GetMapping("/search")
    public ResponseVO search(String FuzzyName){
        MeetingroomQuery query = new MeetingroomQuery();
        query.setNameFuzzy(FuzzyName);
        List<Meetingroom> list = meetingroomService.findListByParam(query);
        return getSuccessResponseVO(list);
    }
    @ApiOperation("获取指定会议室的设备信息")
    @GetMapping("/getDevice")
    public ResponseVO getDevice(Integer roomId){
        RoomdeviceQuery query = new RoomdeviceQuery();
        query.setRoomId(roomId);
        List<Roomdevice> list = roomdeviceService.findListByParam(query);
        List<Device> deviceList = new ArrayList<>();
        for(Roomdevice roomdevice:list){
            Device device = deviceService.getDeviceByDeviceId(roomdevice.getDeviceId());
            deviceList.add(device);

        }
        return getSuccessResponseVO(deviceList);
    }
    @ApiOperation("获取指定会议室还没有装上去的设备信息")
    @GetMapping("/getNoDevice")
    public ResponseVO getDeviceList(Integer roomId){
        RoomdeviceQuery query = new RoomdeviceQuery();
        query.setRoomId(roomId);
        List<Roomdevice> list = roomdeviceService.findListByParam(query);
        DeviceQuery query1 = new DeviceQuery();
        List<Device> deviceList = deviceService.findListByParam(query1);
        Iterator<Device> iterator = deviceList.iterator();
        while (iterator.hasNext()) {
            Device device = iterator.next();
            for (Roomdevice roomdevice : list) {
                if (device.getDeviceId().equals(roomdevice.getDeviceId())) {
                    iterator.remove();
                    break;
                }
            }
        }
        return getSuccessResponseVO(deviceList);
    }
    @ApiOperation("添加指定会议室的指定设备")
    @PostMapping("/addDevice")
    public ResponseVO addDevice(Integer roomId,Integer deviceId){

        Roomdevice testrd=  roomdeviceService.getRoomdeviceByRoomIdAndDeviceId(roomId,deviceId);
        if(testrd!=null){
            throw new BusinessException("这个会议室该设备已存在");
        }
        Roomdevice roomdevice = new Roomdevice();
        roomdevice.setRoomId(roomId);
        roomdevice.setDeviceId(deviceId);
        roomdeviceService.add(roomdevice);
        return getSuccessResponseVO("添加成功");
    }
    @ApiOperation("删除指定会议室的指定设备")
    @PostMapping("/deleteDevice")
    public ResponseVO deleteDevice(Integer roomId,Integer deviceId){
        RoomdeviceQuery query = new RoomdeviceQuery();
        query.setRoomId(roomId);
        query.setDeviceId(deviceId);
        roomdeviceService.deleteRoomdeviceByRoomIdAndDeviceId(roomId,deviceId);
        return getSuccessResponseVO("删除成功");
    }
    @ApiOperation("获取指定会议室的内部环境图片数量")
    @GetMapping("/imageCount")
    public ResponseVO getImageCount(Integer roomId){
        Integer count = roomshowService.getImageCount(roomId);
        return getSuccessResponseVO(count);
    }

    @ApiOperation("获取会议室具体环境内部图片信息")
    @GetMapping("/getImg")
    public ResponseEntity<byte[]> getImg(Integer roomId, Integer index){
        String filename =  roomshowService.getImgName(roomId, index);
        Path path= Paths.get(UPLOAD_PATH);
        try {
            // 遍历目录查找文件
            Optional<Path> foundFile;
            try (Stream<Path> stream = Files.walk(path)) {
                foundFile = stream
                        .filter(Files::isRegularFile)
                        .filter(p -> p.getFileName().toString().equals(filename))
                        .findFirst();
            }

            // 读取文件内容
            Path filePath = foundFile.get();
            byte[] imageBytes = Files.readAllBytes(filePath);

            // 根据后缀确定MIME类型
            String fileExtension = filename.substring(filename.lastIndexOf('.') + 1);

            // 返回图片数据
            return ResponseEntity.ok()
                    .contentType(fileExtension.equalsIgnoreCase("png") ? MediaType.IMAGE_PNG : MediaType.IMAGE_JPEG)
                    .body(imageBytes);

        } catch (IOException e) {
            throw new BusinessException("会议室图片读取失败", e);
        }

    }

    @ApiOperation("增加指定会议室的图片")
    @PostMapping("/addImg")
    public ResponseVO addImg(@RequestParam("file")MultipartFile file,Integer roomId){
        if(file.isEmpty()){
            throw new BusinessException("文件不能为空");
        }
        String originalFileName = file.getOriginalFilename();
        int lastDotIndex = originalFileName.lastIndexOf('.');
        if (lastDotIndex == -1) {
            throw new BusinessException("文件名不合法");
        } else if (lastDotIndex == originalFileName.length() - 1) {
            throw new BusinessException("文件名后缀不能为空");
        }
        String fileExtension = originalFileName.substring(lastDotIndex + 1);
        String newFileName = UUID.randomUUID().toString() + "." + fileExtension;

        Path uploadDir = Paths.get(UPLOAD_PATH);
        try {
            Files.createDirectories(uploadDir);
            Path filePath = uploadDir.resolve(newFileName);
            file.transferTo(filePath.toFile());
        } catch (IOException e) {
            throw new BusinessException("文件上传失败", e);
        }
        roomshowService.addImg(roomId,newFileName);
        return getSuccessResponseVO("上传成功");

    }
    @ApiOperation("删除指定会议室的图片")
    @PostMapping("/deleteImg")
    public ResponseVO deleteImg(Integer roomId,Integer index){
        String fileName =  roomshowService.getImgName(roomId,index);
        if (fileName == null || fileName.isEmpty()) {
            throw new BusinessException("文件名不能为空");
        }
        Path filePath = Paths.get(UPLOAD_PATH).resolve(fileName).normalize();

        if (!filePath.startsWith(Paths.get(UPLOAD_PATH).normalize())) {
            throw new BusinessException("文件路径不合法");
        }
        if (!Files.exists(filePath)) {
            throw new BusinessException("文件不存在");
        }
        try {
            Files.deleteIfExists(filePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        roomshowService.deleteImg(roomId,index);
        return getSuccessResponseVO("删除成功");
    }
    @ApiOperation("发布二级评论")
    @PostMapping("/commentsubmit")
    @GlobalInterceptor(checkLogin = true)
    public ResponseVO commentsubmit(String content,String commentId,String replyId) {
        TokenUserInfoDto userInfoDto = getTokenUserInfo("admin");
        commentService.commentsubmit(content, userInfoDto.getUserId(), commentId, replyId,0);
        return getSuccessResponseVO(null);
    }

    @ApiOperation("查看指定时间的会议室状态")
    @PostMapping("/showStatus")
    public ResponseVO showStatus(Integer roomId, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startDate, @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date endDate) {
        List<StatusVo> list = meetingroomService.showStatus(roomId,startDate,endDate);
        return getSuccessResponseVO(list);

    }


}
